from flask import Blueprint, request, jsonify
import requests
import os
from dotenv import load_dotenv
import logging
import threading
import time
from pathlib import Path
import re

import threading
import sys
import traceback

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

guide_bp = Blueprint('guide', __name__)
load_dotenv()

# 环境变量配置
DEEPSEEK_API_URL = os.getenv("DEEPSEEK_API_URL")
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")

# 提示词目录及缓存
PROMPTS_DIR = Path(__file__).resolve().parent / "prompt"
prompt_cache = {}

# 存储各 session 最后输入时间与上下文
session_activity = {}
lock = threading.Lock()

INACTIVITY_THRESHOLD = 60 # 秒，1 分钟
CHECK_INTERVAL = 1        # 后台检查间隔秒数


def load_prompt(prompt_type="continue"):
    """动态加载提示词文件并缓存"""
    if prompt_type in prompt_cache:
        return prompt_cache[prompt_type]

    prompt_file = PROMPTS_DIR / f"{prompt_type}_suggestions.txt"
    try:
        content = prompt_file.read_text(encoding='utf-8').strip()
        prompt_cache[prompt_type] = content
        return content
    except FileNotFoundError:
        logger.error(f"提示词文件不存在: {prompt_file}")
        return None


def background_checker():
    while True:
        now = time.time()
        # 第一阶段：快速收集需要处理的session（无锁）
        sessions_to_process = []
        with lock:  # 极短时间的锁
            for session_id, data in list(session_activity.items()):
                if (now - data.get('last_input', now) > INACTIVITY_THRESHOLD
                        and not data.get('notified')):
                    sessions_to_process.append((session_id, data.get('context', "")))
                    data['notified'] = True  # 立即标记避免重复

        # 第二阶段：无锁状态下处理（可能耗时）
        for session_id, context in sessions_to_process:
            generate_and_notify(session_id, context)  # 这里可能耗时

        time.sleep(CHECK_INTERVAL)  # 睡眠在锁外


def remove_think_block(text):
    return re.sub(r'<think>.*?</think>\n?', '', text, flags=re.DOTALL)

def generate_and_notify(session_id, context):
    print(f"API URL: {DEEPSEEK_API_URL}")  # 检查是否正确
    print(f"API Key: {'*' * 10}{DEEPSEEK_API_KEY[-4:]}" if DEEPSEEK_API_KEY else "未设置")
    """调用 DeepSeek API 获取续写建议，并通过存储结果供前端查询"""
    system_prompt = load_prompt("continue")
    if not system_prompt:
        logger.error("无法加载续写提示词")
        return

    payload = {
        "model": "DeepSeek-R1",
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": f"当前文章内容：\n{context}\n"}
        ],
        "temperature": 0.7,
        "stream": False
    }
    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json",
        "Accept": "application/json"
    }
    try:
        response = requests.post(
            DEEPSEEK_API_URL,
            headers=headers,
            json=payload,
            timeout=50
        )
        # 4. 检查响应状态
        logger.info(f"API 响应状态码: {response.status_code}")
        logger.info(f"API 响应内容: {response.text[:500]}...")  # 只记录前500字符
        response.raise_for_status()
        # 5. 尝试解析JSON
        try:
            result = response.json()
            print("DEBUG5 - JSON解析完成")  # 检查是否解析成功
            if "choices" not in result:
                raise ValueError("响应中缺少 'choices' 字段")

        except ValueError as e:
            logger.error(f"JSON 解析错误: {str(e)}")
            return jsonify({
                "error": f"API 返回了无效的JSON格式: {response.text[:200]}"
            }), 500
        result = response.json()
        suggestions = result.get('choices', [])[0].get('message', {}).get('content', '')
        cleaned_suggestions = remove_think_block(suggestions)
        with lock:
            session_activity[session_id]['suggestions'] = suggestions
            logger.info(f"Session {session_id} 建议已生成")
    except Exception as e:
        logger.error(f"生成续写建议失败: {e}")

# 启动后台检查线程
threading.Thread(target=background_checker, daemon=True).start()


@guide_bp.route('/input-event', methods=['POST'])
def input_event():
    """
    前端调用：学生每次输入时发送当前文本与 session_id。
    更新最后输入时间和上下文
    """
    data = request.get_json()
    session_id = data.get('session_id')
    context = data.get('context', '')
    if not session_id:
        return jsonify({"error": "缺少 session_id"}), 400

    with lock:
        session_activity.setdefault(session_id, {})
        session_activity[session_id]['last_input'] = time.time()
        session_activity[session_id]['context'] = context
        # 重置触发标志
        session_activity[session_id]['notified'] = False
    return jsonify({"status": "ok"})


@guide_bp.route('/check-suggestions', methods=['POST'])
def check_suggestions():
    """
    前端调用：查询是否有续写建议
    返回建议文本
    """
    data = request.get_json()
    session_id = data.get('session_id') if data else None
    if not session_id:
        return jsonify({"error": "缺少 session_id"}), 400

    with lock:
        data = session_activity.get(session_id, {})
        suggestions = data.get('suggestions')

    if suggestions:
        cleaned_suggestions = remove_think_block(suggestions)
        return jsonify({"suggestions": cleaned_suggestions})
    else:
        return jsonify({"suggestions": None})
